<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card shadow="hover">
      <el-button type="primary" @click="addDialogVisible = true"
        >添加角色</el-button
      >

      <el-table
        :data="rolesList"
        stripe
        border
        style="width: 100%"
        class="el_table"
        height="500"
      >
        <el-table-column type="expand">
          
          <template slot-scope="scope">
            <el-row class="cur_role_right">
              <el-col class="el-col-rights" :span="5">一级权限</el-col>
              <el-col class="el-col-rights" :span="6">二级权限</el-col>
              <el-col class="el-col-rights" :span="13">三级权限</el-col>
            </el-row>

            <el-row 
            v-for="(item1, i1) in scope.row.children" 
            :key="item1.id"
            :class="['bd-bottom', i1 === 0 ? 'bd-top' : '', 'vcenter']"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag type="success"
                closable
                @close="handleDeleteRight(scope.row, item1.id)"
                >{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
                </el-col>
                
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <el-row v-for="(item2, i2) in item1.children" :key="item2.id" :class="[i2 === 0 ? '' : 'bd-top', 'vcenter']">
                  <!-- 渲染二级权限 -->
                  <el-col :span="6">
                    <el-tag type="warning"
                    closable
                    @close="handleDeleteRight(scope.row, item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限 -->
                  <el-col :span="13">
                    <el-tag
                    v-for="(item3, i3) in item2.children"
                    :key="item3.id"
                    closable
                    @close="handleDeleteRight(scope.row, item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              round
              icon="el-icon-edit"
              @click="showEditDialog(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              round
              icon="el-icon-delete"
              @click="showDeleteDialog(scope.row.id)"
              >删除</el-button>
              
            <el-button type="warning" size="mini" round icon="el-icon-setting" @click="showSetRightDialog(scope.row)" 
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色提示框 -->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="40%" @close="handleAddCancel()">

    <el-form :model="addRoleForm" :rules="addRoleRules" ref="addRoleRef" label-width="100px">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="addRoleForm.roleName"></el-input>
      </el-form-item>
      <el-form-item label="角色描述">
        <el-input v-model="addRoleForm.roleDesc"></el-input>
      </el-form-item>
    </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色提示框 -->
    <el-dialog title="编辑角色" :visible.sync="editDialogVisible" width="40%" @close="handleEditCancel()">
      
    <el-form :model="editRoleForm" :rules="editRoleRules" ref="editRoleRef" label-width="100px">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="editRoleForm.roleName"></el-input>
      </el-form-item>
      <el-form-item label="角色描述">
        <el-input v-model="editRoleForm.roleDesc"></el-input>
      </el-form-item>
    </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole()"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 删除角色提示框 -->
    <el-dialog title="删除角色" :visible.sync="delDialogVisible" width="40%">
    <el-form :model="deleteRoleForm" ref="deleteRoleRef" label-width="100px">
      <el-form-item label="角色名称" prop="roleName">
        <el-input disabled v-model="deleteRoleForm.roleName"></el-input>
      </el-form-item>
      <el-form-item label="角色描述">
        <el-input disabled v-model="deleteRoleForm.roleDesc"></el-input>
      </el-form-item>
    </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="delDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="deleteRole()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 设置权限提示框 -->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="40%" @close="setRightDialogClosed()">

      <el-tree
        node-key="id"
        ref="treeRef"
        show-checkbox
        :data="rightsTree"
        :default-expand-all="true"
        :props="rightProps"
        :default-checked-keys="defaultCheckedArray"
        >
      </el-tree>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRight()">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  created() {
    this.getRolesList();
  },
  data() {
    return {
      rolesList: [],
      addDialogVisible: false,
      editDialogVisible: false,
      delDialogVisible: false,
      setRightDialogVisible: false,

      showRoleRights:false,
      addRoleForm:{},
      editRoleForm:{},
      deleteRoleForm:{},
      addRoleRules:{
        roleName:[
          {required: true, message: "请输入角色名称", trigger: "blur"}
        ]
      },
      editRoleRules:{
        roleName:[
          {required: true, message: "请输入角色名称", trigger: "blur"}
        ]
      },
      rightsTree:[],
      rightProps:{
        label:'authName',
        children:'children'
      },
      defaultCheckedArray:[],
      curRoleid:''

    };
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      // console.log(res);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.rolesList = res.data;
    },
    handleAddCancel(){
      this.addRoleForm = {};
      this.$refs.addRoleRef.resetFields();
    },
    addRole(){
      this.$refs.addRoleRef.validate(async (valid) => {
        // console.log(valid);
        if(!valid) return this.$message.error('添加角色信息校验失败');
        const {data: res} = await this.$http.post('roles',{roleName:this.addRoleForm.roleName, roleDesc:this.addRoleForm.roleDesc});
        console.log(res);
        if(res.meta.status !== 201) return this.$message.error('添加角色失败');
        this.$message.success('添加角色成功');
        this.addDialogVisible = false;
        this.getRolesList();
      })
    },
    handleEditCancel(){
      this.$refs.editRoleRef.resetFields();
    },
    async showEditDialog(id){
      this.editDialogVisible = true;
      const {data:res} = await this.$http.get('roles/' + id);
      if(res.meta.status !== 200) return this.$message.error('获取当前角色信息失败');
      this.editRoleForm = res.data;
    },
    editRole(){
      this.$refs.editRoleRef.validate(async (valid) => {
        if(!valid) return this.$message.error('修改角色信息校验失败');
        const {data:res} = await this.$http.put('roles/' + this.editRoleForm.roleId, {roleName:this.editRoleForm.roleName, roleDesc:this.editRoleForm.roleDesc});
        if(res.meta.status !== 200) return this.$message.error('修改角色信息失败');
        this.editDialogVisible = false;
        this.getRolesList();
        this.$message.success('修改角色信息成功');
      })
    },
    async showDeleteDialog(id){
      this.delDialogVisible = true;
      const {data:res} = await this.$http.get('roles/' + id);
      if(res.meta.status !== 200) return this.$message.error('获取当前角色信息失败');
      this.deleteRoleForm = res.data;
      // console.log(this.deleteRoleForm);
    },
    async deleteRole(){
      const {data:res} = await this.$http.delete('roles/' + this.deleteRoleForm.roleId);
      if(res.meta.status !== 200) return this.$message.error('删除角色失败');
      this.delDialogVisible = false;
      this.getRolesList();
      this.$message.success('删除角色成功');
    },
    async handleDeleteRight(role, rightId){
      // console.log(666);
      const res = await this.$confirm('确定删除该权限？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error);
      if(res !== 'confirm'){
        return this.$message.info('取消了删除');
      }
      // this.$message.success('确认了删除');
      const { data:res1 } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`);
      // console.log(res1);
      if(res1.meta.status !== 200) return this.$message.error('删除权限失败');
      // 为了防止当前 下拉框 恢复，我们直接把返回的结果对role的children属性进行更新
      role.children = res1.data;
      this.$message.error('删除权限成功');
    },

    
    async showSetRightDialog(role){
      this.curRoleid = role.id;
      const { data: res } = await this.$http.get('rights/tree');
      if(res.meta.status !== 200) return this.$message.error('获取权限树失败');
      this.rightsTree = res.data;
      this.setRightDialogVisible = true;
      this.getThirdRightKeys(role, this.defaultCheckedArray);
    },

    // 定义获取三级权限id的回调函数
    getThirdRightKeys(node, arr){
      if(!node.children) return arr.push(node.id);
      node.children.forEach(item=>{
        this.getThirdRightKeys(item, arr)
      })
    },
    setRightDialogClosed(){
      this.defaultCheckedArray = [];
    },
    async setRight(){
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];
      // console.log(keys);
      const idStr = keys.join(',');
      const {data:res} = await this.$http.post(`roles/${this.curRoleid}/rights`, {rids:idStr});
      if(res.meta.status !== 200) return this.$message.error('分配权限失败');
      this.getRolesList();
      this.setRightDialogVisible = false;
      this.$message.success('分配权限成功');
    }

  },
};
</script>

<style lang="less" scoped>
.el-table {
  margin-top: 20px;
}

.el-tag{
  margin: 8px;
}

.el-col-rights{
  margin: 8px;
}

.bd-top{
  border-top: 1px solid #eee;
}

.bd-bottom{
  border-bottom: 1px solid #eee;
}

.cur_role_right{
  display:flex;
  justify-content:flex-start;
  color:#b7b7a4;
  font-size:15px;
  padding-left:2px;
}

.vcenter{
  display:flex;
  align-items:center;
}
</style>
